//
//  BonjourObserver.m
//  Do Not Disturb
//
//  Created by Chris Karr on 9/4/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "BonjourObserver.h"
#import "DNDDefines.h"

@implementation BonjourObserver

- (BonjourObserver *) init
{
	if (self = [super init])
	{
		search = [[NSNetServiceBrowser alloc] init];
		services = [[NSMutableArray alloc] init];
		
		searching = NO;
		
		[search setDelegate:self];
	}
	
	return self;
}

- (void) start
{
	searching = YES;
	
	[search searchForServicesOfType:@"_services._dns-sd._udp." inDomain:@""];
}

- (void) scan
{
	if (!searching)
		[self start];
}

- (void) netServiceBrowser:(NSNetServiceBrowser *) netServiceBrowser didFindService:(NSNetService *) netService 
	moreComing:(BOOL) moreServicesComing
{
	if ([netService hostName] == nil && [[netService name] hasPrefix:@"_"])
		[services addObject:[netService name]];
	else
	{
		NSMutableDictionary * dict = [NSMutableDictionary dictionary];
		[dict setValue:[NSDate date] forKey:@"date"];
		[dict setValue:[NSString stringWithFormat:@"Found Bonjour Service Device: %@ [%@]", [netService name], 
						[netService type]] forKey:@"name"];
	
		[[NSDistributedNotificationCenter defaultCenter] postNotificationName:DND_UPDATE object:@"BonjourObserver" userInfo:dict];
	}
	
	if (!moreServicesComing)
	{
		[netServiceBrowser stop];
		
		if ([services count] > 0)
		{
			NSString * type = [services objectAtIndex:0];
			[services removeObject:type];

			type = [type stringByAppendingString:@"._tcp."];
		
			[search searchForServicesOfType:type inDomain:@""];
		}
		else
			searching = NO;
	}
}

- (void)netServiceBrowser:(NSNetServiceBrowser *)netServiceBrowser didNotSearch:(NSDictionary *)errorInfo
{
	NSLog (@"error: %@", errorInfo);
}

- (NSString *) getName
{
	return @"Bonjour";
}

@end
